package org.example.new_hbps_backend_reconstruction.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author 丁利军
 * @date 2025年10月11日 21:44
 * @description TODO: 描述
 */

public class WebSocketMessageSender {
    private static final Logger log = LoggerFactory.getLogger(WebSocketMessageSender.class);

    public WebSocketMessageSender() {
    }

    public static void broadcast(String message) {
        Collection<WebSocketSession> sessions = WebSocketSessionHolder.getSessions();
        Iterator var2 = sessions.iterator();

        while(var2.hasNext()) {
            WebSocketSession session = (WebSocketSession)var2.next();
            send(session, message);
        }

    }

    public static boolean send(Object sessionKey, String message) {
        WebSocketSession session = WebSocketSessionHolder.getSession(sessionKey);
        if (session == null) {
            log.info("[send] 当前 sessionKey：{} 对应 session 不在本服务中", sessionKey);
            return false;
        } else {
            return send(session, message);
        }
    }

//    public static void send(WebSocketSession session, JsonWebSocketMessage message) {
//        ObjectMapper mapper = (ObjectMapper)SpringBeanContextHolder.getBean(ObjectMapper.class);
//
//        try {
//            send(session, mapper.writeValueAsString(message));
//        } catch (JsonProcessingException var4) {
//            throw new RuntimeException(var4);
//        }
//    }

    public static boolean send(WebSocketSession session, String message) {
        if (session == null) {
            log.error("[send] session 为 null");
            return false;
        } else if (!session.isOpen()) {
            log.error("[send] session 已经关闭");
            return false;
        } else {
            try {
                session.sendMessage(new TextMessage(message));
                return true;
            } catch (IOException var3) {
                log.error("[send] session({}) 发送消息({}) 异常", new Object[]{session, message, var3});
                return false;
            }
        }
    }
}

